/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.box2d;

import org.cogaen.core.Core;
import org.cogaen.core.UpdateableService;
import org.cogaen.event.EventManager;
import org.jbox2d.collision.AABB;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.ContactListener;
import org.jbox2d.dynamics.World;
import org.jbox2d.dynamics.contacts.ContactPoint;
import org.jbox2d.dynamics.contacts.ContactResult;

public class PhysicsService implements UpdateableService, ContactListener {

	public static final String NAME = "cogaen.box2d.physicsservice";
	private EventManager eventManager;
	private Core core;
	private World world;

	public static PhysicsService getInstance(Core core) {
		return (PhysicsService) core.getService(NAME);
	}

	public PhysicsService() {
		// TODO remove hard coded world boundaries
		AABB worldBoundaries = new AABB(new Vec2(-1000f, -1000f), new Vec2(1000f, 1000f));
		Vec2 gravity = new Vec2(0, -9.81f);
		
		this.world = new World(worldBoundaries, gravity, true);
		this.world.setContactListener(this);
	}
	
	
	public World getWorld() {
		return this.world;
	}	
	
	public void setGravity(Vec2 gravity) {
		this.world.setGravity(gravity);
		Body body = this.world.getBodyList();
		while (body != null) {
			if (body.isSleeping()) {
				body.wakeUp();
			}
			body = body.getNext();
		}		
	}
	
	public void setGravity(double x, double y) {
		setGravity(new Vec2((float) x, (float) y));
	}	

	public void syncVisibles() {
		Body body = this.world.getBodyList();
		while (body != null) {
			if (!body.isSleeping() && body.getUserData() != null) {
				Vec2 pos = body.getPosition();
				this.eventManager.enqueueEvent( new EntityMovedEvent((String) body.getUserData(), pos.x, pos.y, body.getAngle()) );
			}
			body = body.getNext();
		}
	}
	
	@Override
	public void initialize(Core core) {
		this.core = core;
		this.eventManager = EventManager.getInstance(core);
	}
	
	@Override
	public void update() {
		// TODO Use time service to retrieve current delta time
		this.world.step((float) this.core.getDeltaTime(), 10);
	}

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public void add(ContactPoint contactPoint) {
		String first = (String) contactPoint.shape1.getBody().getUserData();
		String second = (String) contactPoint.shape2.getBody().getUserData();		
		this.eventManager.enqueueEvent( new CollisionEvent(first, second, contactPoint.velocity.lengthSquared()) );
	}

	@Override
	public void persist(ContactPoint contactPoint) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void remove(ContactPoint contactPoint) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void result(ContactResult contactPoint) {
		// TODO Auto-generated method stub
		
	}


}
